//
//  NvTakeImageViewController.m
//  NvSellerShow
//
//  Created by dx on 17/6/26.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvTakeImageViewController.h"
#import "NvTakeImagePreview.h"
#import "NvGridView.h"
//#import "UIImage+Resize.h"
#import <AVFoundation/AVFoundation.h>
#import "Utils.h"

@interface NvTakeImageViewController ()

//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property (nonatomic, strong) AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property (nonatomic, strong) AVCaptureDeviceInput *input;

//输出图片
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property (nonatomic, strong) AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;
//拍照的图片
@property (nonatomic, strong) UIImage *takeImage;

@property (nonatomic, assign) BOOL isflashOn;
@property (nonatomic ,assign) AVCaptureDevicePosition currentDevicePosition;
@property (nonatomic, strong) NvTakeImagePreview *takeImagePreview;
@property (nonatomic, strong) NvGridView *gridView;
@property (weak, nonatomic) IBOutlet UIImageView *mediaView;
@property (weak, nonatomic) IBOutlet UIButton *takeImageBtn;
@property (weak, nonatomic) IBOutlet UIImageView *backImage;
@property (weak, nonatomic) IBOutlet UIImageView *tipRotateImageView;
@property (weak, nonatomic) IBOutlet UILabel *tipRotateLabel;
- (IBAction)changeCamera:(id)sender;
- (IBAction)showGrid:(id)sender;
- (IBAction)flashOn:(id)sender;


@end

@implementation NvTakeImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.takeImageBtn addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.takeImagePreview];
    self.takeImagePreview.frame = self.view.bounds;
    self.takeImagePreview.delegate = self;
    
    [self.backImage addTapGestureRecognizer:@selector(back) target:self];
    
    [self.view addSubview:self.gridView];

    self.gridView.frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height-64);
    [self.view bringSubviewToFront:self.takeImageBtn];
    
    _isflashOn = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    //只有16：9和9：16的拍摄会进入这个页面
    if (self.editmode == NvSSVideoCreateScaleVertical) {//竖屏拍摄
        self.tipRotateLabel.text = @"请竖屏拍摄(关闭屏幕方向锁定)";
        if ([[UIDevice currentDevice] orientation]==UIDeviceOrientationPortrait) {
            self.tipRotateImageView.hidden = YES;
            self.tipRotateLabel.hidden = YES;
            self.takeImageBtn.hidden = NO;
        } else {
            self.tipRotateImageView.hidden = NO;
            self.tipRotateLabel.hidden = NO;
            self.takeImageBtn.hidden = YES;
        }
    } else {//横屏拍摄
        self.tipRotateLabel.text = @"请横屏拍摄(关闭屏幕方向锁定)";
        if ([[UIDevice currentDevice] orientation]==UIDeviceOrientationLandscapeLeft) {
            self.tipRotateImageView.hidden = YES;
            self.tipRotateLabel.hidden = YES;
            self.takeImageBtn.hidden = NO;
        } else {
            self.tipRotateImageView.hidden = NO;
            self.tipRotateLabel.hidden = NO;
            self.takeImageBtn.hidden = YES;
        }
    }
}

- (void)orientChange:(NSNotification *)noti {
    UIDeviceOrientation  orient = [UIDevice currentDevice].orientation;

    if (self.editmode == NvSSVideoCreateScaleVertical) {
        switch (orient) {
            case UIDeviceOrientationPortrait:
                self.tipRotateImageView.hidden = YES;
                self.tipRotateLabel.hidden = YES;
                self.takeImageBtn.hidden = NO;
                break;
                
            default:
                self.tipRotateImageView.hidden = NO;
                self.tipRotateLabel.hidden = NO;
                self.takeImageBtn.hidden = YES;
                break;
        }
    } else {
        switch (orient) {
            case UIDeviceOrientationLandscapeLeft:
                self.tipRotateImageView.hidden = YES;
                self.tipRotateLabel.hidden = YES;
                self.takeImageBtn.hidden = NO;
                break;
                
            default:
                self.tipRotateImageView.hidden = NO;
                self.tipRotateLabel.hidden = NO;
                self.takeImageBtn.hidden = YES;
                break;
        }
    }
    
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self cameraDistrict];
}

- (void)cameraDistrict {
    //    AVCaptureDevicePositionBack  后置摄像头
    //    AVCaptureDevicePositionFront 前置摄像头
    self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    self.currentDevicePosition = AVCaptureDevicePositionBack;
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    //输入输出设备结合
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.imageOutput]) {
        [self.session addOutput:self.imageOutput];
    }
    //预览层的生成
    if (self.editmode == NvSSVideoCreateScaleHorizontal) {//16:9默认大小即可
    } else if (self.editmode == NvSSVideoCreateScaleVertical) {
        self.mediaView.width_LL = self.view.frame.size.width;
        self.mediaView.height_LL = self.mediaView.width_LL*16.0/9;
    }else{//1:1不在这个类处理
    }
    
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, self.mediaView.width_LL, self.mediaView.height_LL);
    self.previewLayer.videoGravity = AVLayerVideoGravityResize;
    [self.mediaView.layer insertSublayer:self.previewLayer below:self.view.layer];
    
    //设备取景开始
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        //自动闪光灯，
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡,但是好像一直都进不去
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ){
            return device;
        }
    return nil;
}

- (void)takePicture {
    self.takeImagePreview.hidden = NO;
    self.gridView.hidden = YES;
    AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (!conntion) {
        NSLog(@"拍照失败!");
        return;
    }
    AVCaptureVideoOrientation orientation = [self videoOrientationFromCurrentDeviceOrientation];
    if(orientation >= 0)
        [conntion setVideoOrientation:orientation];
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
     {
         if (imageDataSampleBuffer == nil){
             NSLog(@"imageDataSampleBuffer is nil");
             return ;
         }
         [self.session stopRunning];
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
         _takeImage = [UIImage imageWithData:imageData];
         UIImage *ii = [_takeImage normalizedImage];
         self.takeImagePreview.previewImage.image = ii;
     }];
}

- (AVCaptureVideoOrientation) videoOrientationFromCurrentDeviceOrientation {
    switch ([[UIDevice currentDevice] orientation]) {
        case UIDeviceOrientationPortrait: {
            return AVCaptureVideoOrientationPortrait;
        }
        case UIDeviceOrientationLandscapeLeft: {
            return AVCaptureVideoOrientationLandscapeRight;
        }
        case UIDeviceOrientationLandscapeRight: {
            return AVCaptureVideoOrientationLandscapeLeft;
        }
        case UIDeviceOrientationPortraitUpsideDown: {
            return AVCaptureVideoOrientationPortraitUpsideDown;
        }
        default:
            return AVCaptureVideoOrientationPortrait;
            //此处UIDeviceOrientationLandscapeLeft对应AVCaptureVideoOrientationLandscapeRight为iosSDK问题，并非编写错误
    }
}

#pragma mark - takeImagePreviewDelegate
- (void)takeImagePreview:(NvTakeImagePreview*)takeImagePreview clickCancel:(UIButton*)cancelButton {
    self.takeImagePreview.hidden = YES;
    [self.session startRunning];
}

- (void)takeImagePreview:(NvTakeImagePreview*)takeImagePreview clickSure:(UIButton*)SureButton {
    if ([self.delegate respondsToSelector:@selector(nvTakeImageViewController: didFinishTakeImage:)]) {
        [self.delegate nvTakeImageViewController:self didFinishTakeImage:takeImagePreview.previewImage.image];
    }
}

#pragma mark - Getter

- (NvTakeImagePreview *)takeImagePreview {
    if (!_takeImagePreview) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        _takeImagePreview = [[myBundle loadNibNamed:@"NvTakeImagePreview" owner:self options:nil] lastObject];
    }
    NSLog(@"%@",_takeImagePreview);
    return _takeImagePreview;
}

- (NvGridView *)gridView {
    if (!_gridView) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        _gridView = [[myBundle loadNibNamed:@"NvGridView" owner:self options:nil] lastObject];
    }
    return _gridView;
}

#pragma mark - targetClick
- (IBAction)changeCamera:(id)sender {
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        //给摄像头的切换添加翻转动画
        CATransition *animation = [CATransition animation];
        animation.duration = .5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        //拿到另外一个摄像头位置
        AVCaptureDevicePosition position = _currentDevicePosition;
        if (position == AVCaptureDevicePositionFront){
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;//动画翻转方向
            _currentDevicePosition = AVCaptureDevicePositionBack;
        } else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;//动画翻转方向
            _currentDevicePosition = AVCaptureDevicePositionFront;
        }
        //生成新的输入
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
        [self.previewLayer addAnimation:animation forKey:nil];
        if (newInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:self.input];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
                self.input = newInput;
                
            } else {
                [self.session addInput:self.input];
            }
            [self.session commitConfiguration];
            
        } else if (error) {
            NSLog(@"toggle carema failed, error = %@", error);
        }
    }
}

- (IBAction)showGrid:(UIButton*)sender {
    self.gridView.hidden = sender.selected;
    sender.selected = !sender.selected;
}

- (IBAction)flashOn:(UIButton*)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    if ([_device lockForConfiguration:nil]) {
        if (_isflashOn) {
            if ([_device isFlashModeSupported:AVCaptureFlashModeOff]) {
                [_device setFlashMode:AVCaptureFlashModeOff];
                _isflashOn = NO;

                [sender setImage:[UIImage imageWithContentsOfFile:[myBundle pathForResource:@"cam_flashoff" ofType:@"png"]] forState:UIControlStateNormal];
            }
        }else{
            if ([_device isFlashModeSupported:AVCaptureFlashModeOn]) {
                [_device setFlashMode:AVCaptureFlashModeOn];
                _isflashOn = YES;
                [sender setImage:[UIImage imageWithContentsOfFile:[myBundle pathForResource:@"cam_flashon" ofType:@"png"]] forState:UIControlStateNormal];
            }
        }
        [_device unlockForConfiguration];
    }
}
@end
